package com.ar4j.spring;

import java.lang.reflect.Method;

import org.springframework.transaction.annotation.TransactionAnnotationParser;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttributeSource;

/**
 * A transaction attribute source able to parse an active record's transaction annotation.
 */
public class ActiveRecordTransactionAttributeSource implements TransactionAttributeSource {
  private TransactionAnnotationParser parser;
  
  /**
   * Construct a transaction attribute source using the given parser to parse transaction annotations
   * from either an active record's base class or method.
   */
  public ActiveRecordTransactionAttributeSource(TransactionAnnotationParser parser) {
    this.parser = parser;
  }
  
  /**
   * Searches for transaction annotations (using the parser given when constructed) first on the given method.
   * If none are found on the method, the baseClass is scanned, if it is not null.
   * 
   * @see org.springframework.transaction.interceptor.TransactionAttributeSource#getTransactionAttribute(java.lang.reflect.Method, java.lang.Class)
   */
  @SuppressWarnings("unchecked")
  @Override
  public TransactionAttribute getTransactionAttribute(Method method, Class baseClass) {
    TransactionAttribute out = parser.parseTransactionAnnotation(method);
    if(out == null && baseClass != null) {
      out = parser.parseTransactionAnnotation(baseClass);
    }
    
    return out;
  }

}
